package com.lgkj.ui.meitao;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.lgkj.R;
import com.lgkj.adapter.CkAdapter;
import com.lgkj.adapter.HotAdapter;
import com.lgkj.adapter.MemberAdapter;
import com.lgkj.adapter.NewGoodsAdapter;
import com.lgkj.adapter.NewProdectAdapter;
import com.lgkj.adapter.SearShopAdapter;
import com.lgkj.bean.SearchShopBean;
import com.lgkj.bean.meitao.GoodsTypeBean;
import com.lgkj.bean.meitao.HomeGoodsBean;
import com.lgkj.bean.meitao.SearchGoods;
import com.lgkj.ui.AdTextActivity;
import com.lgkj.ui.GoodsListActivity;
import com.lgkj.ui.ImageBrowseActivity;
import com.lgkj.ui.PlayGameActivity;
import com.lgkj.ui.ShopDetailsActivity;
import com.lgkj.ui.shop.FootActivity;
import com.lgkj.ui.shop.ShopDetailsActivivty;
import com.lgkj.utils.CityJson;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.CommonUtils;
import com.lgkj.utils.HttpUtils;
import com.lgkj.utils.SharedPreferencesUtils;
import com.lgkj.view.MyListView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoaderInterface;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/19 0019.
 */

public class HomeFragment extends Fragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "HomeFragment";
    @BindView(R.id.sl_banner)
    Banner slBanner;
    Unbinder unbinder;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.lv_name)
    ListView lvName;
    @BindView(R.id.tv_adress)

    TextView tvAdress;
    @BindView(R.id.ll_new_product)
    MyListView llNewProduct;
    private NewGoodsAdapter newProdectAdatapter;
    @BindView(R.id.ll_hot_product)
    GridView llHotProduct;
    @BindView(R.id.ll_vip_product)
    GridView llVipProduct;
    @BindView(R.id.ll_mark_product)
    GridView llMarkProduct;


    private HotAdapter hotAdapter;
    private MemberAdapter memberAdapter;
    private CkAdapter ckAdapter;
    private List<String> slideUrl;
    private SearchGoods searchShopBean;
    private String lat = "31.400761", lng = "104.823364";
    private View view;
    private SearShopAdapter searShopAdapter;
    private HomeFragmentUtils homeFragmentUtils;
    private HomeGoodsBean homeBean;
    public static int typeTitleImg = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_home_mei_fragment, null);
        unbinder = ButterKnife.bind(this, view);
        searShopAdapter = new SearShopAdapter(getContext());
        homeFragmentUtils = new HomeFragmentUtils(getActivity());
        lvName.setAdapter(searShopAdapter);
        initView();
        initData();
        lvName.setVisibility(View.GONE);
        return view;
    }

    private void initView() {
        lat = SharedPreferencesUtils.getParam(getActivity(), "lat", "31.400761").toString();
        lng = SharedPreferencesUtils.getParam(getActivity(), "lng", "104.823364").toString();
        Log.i(TAG, "initView: " + lat + "," + lng);
        slideUrl = new ArrayList<>();
        combination();
        initSeach();
        String city = SharedPreferencesUtils.getParam(getActivity(), "city", "绵阳").toString();
        tvAdress.setText(city);
        hotAdapter = new HotAdapter(getActivity());
        memberAdapter = new MemberAdapter(getActivity());
        ckAdapter = new CkAdapter(getActivity());
        llHotProduct.setAdapter(hotAdapter);
        llVipProduct.setAdapter(memberAdapter);
        llMarkProduct.setAdapter(ckAdapter);

        newProdectAdatapter = new NewGoodsAdapter(getActivity());
        llNewProduct.setAdapter(newProdectAdatapter);
        llNewProduct.setOnItemClickListener(this);
        llHotProduct.setOnItemClickListener(this);
        llVipProduct.setOnItemClickListener(this);
        llMarkProduct.setOnItemClickListener(this);


    }

    private void initData() {
        hotAdapter = new HotAdapter(getActivity());
        memberAdapter = new MemberAdapter(getActivity());
        ckAdapter = new CkAdapter(getActivity());
        llHotProduct.setAdapter(hotAdapter);
        llVipProduct.setAdapter(memberAdapter);
        llMarkProduct.setAdapter(ckAdapter);
        combinationGoods();
    }

    /**
     */
    private void ShowChoise() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("选择一个城市");
        builder.setItems(CityJson.getcity(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvAdress.setText(CityJson.getcity()[which]);
                lat = CityJson.getLat()[which];
                lng = CityJson.getLng()[which];
                Log.i(TAG, "onClick: " + lat + ",lng:" + lng);
                intBanner();


            }
        });
        builder.show();
    }

    private void initSeach() {
        etName.setOnKeyListener(new View.OnKeyListener() {//输入完后按键盘上的搜索键【回车键改为了搜索键】

            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    //先隐藏键盘
                    ((InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getActivity().getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    seach();
                    return true;
                }
                return false;
            }
        });

        lvName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SearchGoods.DataBeanX.DataBean bean = searShopAdapter.getItem(i);
                Log.i(TAG, "onItemClick: " + bean.toString());
                Intent intent = new Intent(getActivity(), ShopDetailsActivivty.class);
                intent.putExtra("goodsId", bean.getId());
                startActivity(intent);
                lvName.setVisibility(View.GONE);

            }
        });
    }

    private void seach() {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(getActivity()));
        map.put("keywords", etName.getText().toString());
        HttpUtils.postHttp(map, CommonConstant.searchShop, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                Gson mGson = new Gson();
                if (jsonObject.optInt("code") == 0) {
                    lvName.setVisibility(View.VISIBLE);
                    searchShopBean = mGson.fromJson(String.valueOf(jsonObject), SearchGoods.class);
                    if (searchShopBean != null && searchShopBean.getData() != null && searchShopBean.getData().getData() != null) {
                        searShopAdapter.setData(searchShopBean.getData().getData());
                        searShopAdapter.notifyDataSetChanged();
                        combination();
                    }
                }

            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_adress, R.id.tv_item1, R.id.tv_item2, R.id.tv_item3, R.id.ib_saoyisao, R.id.iv_new_product, R.id.iv_hot_product, R.id.iv_vip_product, R.id.iv_mark_product, R.id.ll_item1, R.id.ll_item2, R.id.ll_item3, R.id.ll_item4})
    public void onClick(View view) {
        GoodsListActivity.is_new = "-1";
        GoodsListActivity.is_hot = "-1";
        GoodsListActivity.type_id = "-1";
        GoodsListActivity.reg_level = "-1";
        switch (view.getId()) {
            case R.id.ll_item1:
                typeTitleImg=0;
                GoodsListActivity.type_id = "1";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
            case R.id.ll_item2:
                typeTitleImg=1;
                GoodsListActivity.type_id = "2";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
            case R.id.ll_item3:
                typeTitleImg=2;
                GoodsListActivity.type_id = "3";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
            case R.id.ll_item4:
                typeTitleImg=3;
                GoodsListActivity.type_id = "4";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
            case R.id.tv_adress:
                ShowChoise();
                break;
            case R.id.tv_item1:
                startActivity(new Intent(getActivity(), AdTextActivity.class));
                break;
            case R.id.tv_item2:
//                startActivity(new Intent(getActivity(), ShopPlayActivity.class));
                break;
            case R.id.tv_item3:
                startActivity(new Intent(getActivity(), PlayGameActivity.class));
                break;
            case R.id.ib_saoyisao:
                new IntentIntegrator(getActivity()).initiateScan();
//                startActivity(new Intent(getActivity(), ControlActivity.class));
                break;
            case R.id.iv_new_product:  //新品上市
                GoodsListActivity.is_new = "1";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                typeTitleImg=4;
                break;
            case R.id.iv_hot_product:  //热门推荐
                typeTitleImg=5;
                GoodsListActivity.is_hot = "1";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
            case R.id.iv_vip_product:
                typeTitleImg=6;
                GoodsListActivity.reg_level = "1";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
            case R.id.iv_mark_product:
                typeTitleImg=7;
                GoodsListActivity.reg_level = "2";
                startActivity(new Intent(getActivity(), GoodsListActivity.class));
                break;
        }
    }

    /**
     * 首页轮播
     */
    private void combination() {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(getActivity()));
        map.put("lat", lat);
        map.put("lng", lng);
        HttpUtils.postHttp(map, CommonConstant.combination, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                if (jsonObject.optInt("code") == 0) {
                    JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("banner");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        slideUrl.add(jsonArray.optJSONObject(i).optString("banner_img_id"));
                        intBanner();
                    }
                }

            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }


    private void combinationGoods() {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(getActivity()));
        map.put("lat", lat);
        map.put("lng", lng);
        HttpUtils.postHttp(map, CommonConstant.combinationgoods, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                if (jsonObject.optInt("code") == 0) {
                    homeBean = new Gson().fromJson(String.valueOf(jsonObject), HomeGoodsBean.class);
                    newProdectAdatapter.setData(homeBean.getData().getNews_list());
                    hotAdapter.setData(homeBean.getData().getHot_list());
                    memberAdapter.setData(homeBean.getData().getMember_list());
                    ckAdapter.setData(homeBean.getData().getCk_list());
                    newProdectAdatapter.notifyDataSetChanged();
                    hotAdapter.notifyDataSetChanged();
                    memberAdapter.notifyDataSetChanged();
                    ckAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void errorHttp(String msg) {

            }
        });

    }


    private void getGoodsType() {
        CommonUtils.showDiaLog(getActivity(), "正在查询");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(getActivity()));
        HttpUtils.postHttp(map, CommonConstant.goodsTypeList, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                if (jsonObject.optInt("code") == 0) {
                    GoodsTypeBean goodsTypeBean = new Gson().fromJson(String.valueOf(jsonObject), GoodsTypeBean.class);
                }

            }

            @Override
            public void errorHttp(String msg) {
                Toast.makeText(getActivity(), "查询失败", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void intBanner() {
        if (slideUrl.size() == 0) {
            return;
        }
        if (slBanner == null) {
            return;
        }
        slBanner.isAutoPlay(true);
        //设置轮播时间
        slBanner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        slBanner.setIndicatorGravity(BannerConfig.CENTER);
        slBanner.setImageLoader(new ImgLoader());
        slBanner.setImages(slideUrl);
        slBanner.start();
        this.slBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                try {
                    Intent intent = new Intent(getActivity(), ImageBrowseActivity.class);
                    intent.putExtra("image_url", slideUrl.get(position));
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(getActivity(), slBanner, "shareNames").toBundle());
//                    startActivity(intent);
                } catch (Exception e) {
                    Log.e(TAG, "OnBannerClick: slBanner超出数组");
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String goodsId = "";
        switch (adapterView.getId()) {
            case R.id.ll_new_product:
                goodsId = newProdectAdatapter.getItem(i).getId();
                break;
            case R.id.ll_hot_product:
                goodsId = hotAdapter.getItem(i).getId();
                break;
            case R.id.ll_vip_product:
                goodsId = memberAdapter.getItem(i).getId();
                break;
            case R.id.ll_mark_product:
                goodsId = ckAdapter.getItem(i).getId();
                break;
        }
        Log.i(TAG, "onItemClick: " + goodsId);
        Intent intent = new Intent(new Intent(getActivity(), ShopDetailsActivivty.class));
        intent.putExtra("goodsId", goodsId);
        startActivity(intent);
    }


    private class ImgLoader implements ImageLoaderInterface {
        @Override
        public void displayImage(Context context, Object path, View imageView) {
            if (context != null) {
                CommonUtils.LoadImage(getContext(), (ImageView) imageView, ((String) path), R.mipmap.defult_banner);
            }
        }

        @Override
        public View createImageView(Context context) {
            return null;
        }
    }


}
